package core

import (
	"fmt"
	"log"
	"math"
	"mytool/base"
	"strings"
	"unicode/utf8"

	"github.com/signintech/gopdf"
)

func splitText(content string, limit int) []string {
	var lines []string
	line := ""
	for _, char := range content {
		if utf8.RuneCountInString(line) >= limit {
			lines = append(lines, line)
			line = ""
		}
		line += string(char)
	}
	lines = append(lines, line)
	return lines
}

const gDpi = 72.0         // 分辨率
const gUnit = 25.4        // 一英寸的毫米数
var mBackboneWidth = 35.0 // 脊梁宽度
var mPageWidth float64    // 页面宽度
var mPaneHeight float64   //画布高度
var mPaneWidth float64    //画布宽度

// 设置页面大小
// sizeType 1:A4 2:A5 3:B5
func setSize(sizeType int) {
	var w, h float64
	switch sizeType {
	case 1: // A4
		w = 210
		h = 297
	case 2: // A5
		w = 148.5
		h = 210
	case 3: // B5
		w = 182
		h = 257
	}
	mPageWidth = getNumByMM(w)
	mPaneHeight = getNumByMM(h)
	mPaneWidth = mPageWidth*2 + mBackboneWidth
}

// 获取毫米对应的像素数量
func getNumByMM(mm float64) float64 {
	return mm / gUnit * gDpi
}

// 获取纸张厚度
func getPaperThickness(pageType string) float64 {
	var thickness float64
	switch pageType {
	case "70g":
		thickness = 0.09
	case "80g":
		thickness = 0.104
	case "100g":
		thickness = 0.12
	case "120g":
		thickness = 0.15
	case "铜版纸 128g":
		thickness = 0.11
	case "铜版纸 157g":
		thickness = 0.13
	case "铜版纸 200g":
		thickness = 0.20
	case "铜版纸 250g":
		thickness = 0.25
	case "铜版纸 300g":
		thickness = 0.30
	}
	return thickness / gUnit * gDpi
}

func CoverGenerateCmd(args []string) (err error) {
	fmt.Println("welcome")
	pageNum := 100.0                           // 页数
	pagerThickness := getPaperThickness("80g") // 纸张厚度
	mBackboneWidth = pagerThickness * pageNum  // 脊梁宽度
	fontSize := 30.0                           // 字体大小
	var mIsAutoBreak = false                   // 是否自动换行

	setSize(1) // 设置页面大小

	pdf := gopdf.GoPdf{}
	pdf.Start(gopdf.Config{PageSize: gopdf.Rect{W: mPaneWidth, H: mPaneHeight}}) //595.28, 841.89 = A4
	pdf.AddPage()

	// 画脊梁
	pdf.SetLineWidth(0.1)
	pdf.SetLineType("dashed")
	pdf.Line(mPageWidth, 0, mPageWidth, mPaneHeight)
	targetX := mPageWidth + mBackboneWidth
	pdf.Line(targetX, 0, targetX, mPaneHeight)

	err = pdf.AddTTFFont("wts11", "/Users/ac/work/code/frontend/electron-print-client/resources/ttf.ttf")
	if err != nil {
		log.Print(err.Error())
		return
	}

	err = pdf.SetFont("wts11", "", fontSize)
	if err != nil {
		log.Print(err.Error())
		return
	}

	str := "你好呀我是封面\n你好呀我是封面你好呀\n\n(副本)"
	textWidth, _ := pdf.MeasureTextWidth(str)                                  // 文字宽度
	textHeight, _ := pdf.MeasureCellHeightByText(str)                          // 文字高度
	charNum := utf8.RuneCountInString(str)                                     // 字符数
	charWidth := textWidth / float64(charNum)                                  // 每个字的宽度
	lineCharNum := int(math.Ceil((mPageWidth - getNumByMM(25)*2) / charWidth)) // 每行多少个字
	fmt.Println("每行的字数", lineCharNum)

	var strArr []string
	if mIsAutoBreak {
		strArr = splitText(str, lineCharNum)
	} else { //手动根据换行符分割
		strArr = strings.Split(str, "\n")
	}
	fmt.Printf("文字宽度：%f,文字高度：%f", textWidth, textHeight)

	y := (mPaneHeight-textHeight)/2 - (getNumByMM(70))
	x := mPageWidth + mBackboneWidth

	fmt.Println(mPaneWidth / 2)
	for _, str := range strArr {
		pdf.SetX(x)
		pdf.SetY(y)
		pdf.CellWithOption(&gopdf.Rect{
			W: mPageWidth,
			H: textHeight,
		}, str, gopdf.CellOption{Align: gopdf.Center | gopdf.Middle})
		y += textHeight
	}

	pdf.WritePdf("hello.pdf")
	fmt.Printf("处理完成 ")
	return nil
}

func CoverGenerate() []*base.Option {
	return []*base.Option{
		&base.Option{"CoverGenerate", CoverGenerateCmd, "封面拼版"},
	}
}
